package com.wenqian.server.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

// HTTP响应的构建与封装 : 处理好发出去
public class HttpResponse {
    private String version = "HTTP/1.1";
    private int statusCode;
    private String statusMessage;
    private Map<String, String> headers = new HashMap<>();
    private byte[] body;

    public HttpResponse() {
        // 默认通用头
        this.headers.put("Server", "SimpleJavaHttpServer");
    }

    public void setStatusCode(int code, String message){
        this.statusCode = code;
        this.statusMessage = message;
    }

    public void addHeader(String key, String value){
        this.headers.put(key, value);
    }

    public void setBody(byte[] body){
        this.body = body;
        addHeader("Content-Length", String.valueOf(body.length));
    }

    public void writeTo(OutputStream out) throws IOException {
        // PrintWriter : 向输出流写入格式化的文本数据
        // 1. 自动刷新缓存区
        // 2. 支持写入字符串、数字、布尔值等，并自动转换为文本格式。
        PrintWriter writer = new PrintWriter(out);

        // 1. 写入状态行
        writer.print(version + " " + statusCode + " " + statusMessage + "\r\n");

        // 2. 写入相应头
        for (Map.Entry<String, String> entry : headers.entrySet()){
            writer.print(entry.getKey() + ": " + entry.getValue() + "\r\n");
        }

        // 3. 写入空行，分隔头和体
        writer.print("\r\n");
        writer.flush();

        // 4. 写入响应体
        if (body != null){
            out.write(body);
        }
        out.flush();
    }

}
